<template>
  <div class="vehicle-register-bg">
    <el-card class="vehicle-register-card">
      <div class="vehicle-register-header">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <div class="vehicle-register-title">车辆信息录入</div>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="vehicle-form">
        <!-- 车辆照片上传 -->
        <el-form-item label="车辆照片" prop="avatar" class="avatar-form-item">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:8000/login/users/imgurl/"
            :show-file-list="false"
            :on-success="handleIDSuccess"
          >
            <template #default>
              <img v-if="img_url" :src="img_url" class="avatar" />
              <div v-else class="avatar-upload-btn">
                <el-icon><Plus /></el-icon>
                <span>上传车辆照片</span>
              </div>
            </template>
          </el-upload>
          <div class="upload-tip">
            <p>请上传清晰的车辆照片，系统将自动识别车牌号和车辆信息</p>
            <p>支持 JPG、PNG 格式，文件大小不超过 5MB</p>
          </div>
        </el-form-item>

        <!-- 识别结果展示 -->
        <div v-if="recognitionResult" class="recognition-result">
          <el-divider>识别结果</el-divider>
          
          <!-- 车牌识别结果 -->
          <el-form-item label="车牌号码" prop="plate_number">
            <el-input 
              v-model="form.plate_number" 
              placeholder="系统自动识别或手动输入"
              :readonly="recognitionLoading"
            />
          </el-form-item>

          <!-- 车辆型号 -->
          <el-form-item label="车辆型号" prop="model">
            <el-input 
              v-model="form.model" 
              placeholder="系统自动识别或手动输入"
              :readonly="recognitionLoading"
            />
          </el-form-item>

          <!-- 车辆颜色 -->
          <el-form-item label="车辆颜色" prop="color">
            <el-select v-model="form.color" placeholder="请选择车辆颜色" style="width: 100%">
              <el-option label="白色" value="白色" />
              <el-option label="黑色" value="黑色" />
              <el-option label="银色" value="银色" />
              <el-option label="灰色" value="灰色" />
              <el-option label="红色" value="红色" />
              <el-option label="蓝色" value="蓝色" />
              <el-option label="绿色" value="绿色" />
              <el-option label="黄色" value="黄色" />
              <el-option label="棕色" value="棕色" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <el-form-item class="submit-section">
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitLoading"
            :disabled="!canSubmit"
            size="large"
          >
            {{ submitLoading ? '提交中...' : '提交审核' }}
          </el-button>
          <el-button @click="resetForm" size="large">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { vehicleAPI } from '@/api/vehicle'
import {http} from "@/utils/request.js";

const router = useRouter()
const formRef = ref()
const img_url=ref()
// 表单数据
const form = ref({
  plate_number: '',
  model: '',
  color: '',
  user_id: localStorage.getItem('userid') || ''
})

// 表单验证规则
const rules = {
  plate_number: [
    { required: true, message: '请输入车牌号码', trigger: 'blur' },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/, message: '请输入正确的车牌号码格式', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请输入车辆型号', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择车辆颜色', trigger: 'change' }
  ]
}

// 上传相关
const recognitionLoading = ref(false)
const submitLoading = ref(false)
const recognitionResult = ref(false)
const recognitionDetails = ref(null)

// 计算属性
const canSubmit = computed(() => {
  return form.value.plate_number &&
         form.value.model &&
         form.value.color &&
         img_url.value &&
         !submitLoading.value
})

function handleIDSuccess(res) {
  img_url.value = "http://" + res.url
  console.log('图片上传成功，URL:', img_url.value)

  ElMessage.success('图片上传成功，开始识别车辆信息...')

  // 自动开始车辆识别
  recognizeVehicleByUrl(img_url.value)
}

// 车辆识别（通过URL）
async function recognizeVehicleByUrl(imageUrl) {
  if (!imageUrl) return

  recognitionLoading.value = true

  try {
    const data = {
      img_url: imageUrl,
      user_id: form.value.user_id
    }

    ElMessage.info('正在识别车辆信息，请稍候...')

    const response = await vehicleAPI.recognizeVehicle(data)
    
    if (response.data && response.data.recognition_data) {
      const { recognition_data, plate_result, car_result, ocr_result } = response.data

      // 填充识别结果到表单
      form.value.plate_number = recognition_data.plate_number || ''
      form.value.model = recognition_data.vehicle_model || ''
      form.value.color = recognition_data.vehicle_color || ''

      recognitionResult.value = true
      recognitionDetails.value = {
        plate_result,
        car_result,
        ocr_result
      }

      ElMessage.success('车辆信息识别完成！请检查并确认信息')
    }
  } catch (error) {
    console.error('车辆识别失败:', error)
    ElMessage.error('车辆识别失败，请手动填写信息')
    recognitionResult.value = true // 仍然显示表单让用户手动填写
  } finally {
    recognitionLoading.value = false
  }
}

// 提交表单
async function submitForm() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (!img_url.value) {
      ElMessage.warning('请先上传车辆照片')
      return
    }
    
    await ElMessageBox.confirm(
      '确认提交车辆信息进行审核吗？',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    submitLoading.value = true
    
    // 如果还没有进行识别，先进行识别
    if (!recognitionResult.value && img_url.value) {
      await recognizeVehicleByUrl(img_url.value)
    }

    // 提交车辆信息到数据库
    const submitData = {
      user_id: form.value.user_id,
      plate_number: form.value.plate_number,
      model: form.value.model,
      color: form.value.color,
      image_url: img_url.value
    }

    console.log('提交的数据:', submitData)

    const submitResponse = await vehicleAPI.submitVehicle(submitData)

    console.log('提交响应:', submitResponse)

    if (submitResponse.data) {
      ElMessage.success('车辆信息提交成功，请等待审核')
      router.push('/vehicle/list')
    } else {
      ElMessage.error('提交失败，请重试')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  resetFormData()
  img_url.value = null
  recognitionResult.value = false
  recognitionDetails.value = null
}

function resetFormData() {
  form.value = {
    plate_number: '',
    model: '',
    color: '',
    user_id: localStorage.getItem('userid') || ''
  }
}

function goBack() {
  router.go(-1)
}

onMounted(() => {
  if (!form.value.user_id) {
    ElMessage.error('请先登录')
    router.push('/login')
  }
})
</script>

<style scoped>
.vehicle-register-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.vehicle-register-card {
  width: 100%;
  max-width: 800px;
  border-radius: 24px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1), 0 8px 32px rgba(0, 0, 0, 0.08);
  padding: 40px;
  position: relative;
  z-index: 1;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.vehicle-register-header {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
}

.vehicle-register-title {
  font-size: 28px;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin: 0 auto;
  letter-spacing: 2px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.upload-section {
  width: 100%;
}

.upload-tip {
  margin-top: 12px;
  font-size: 12px;
  color: #666;
  line-height: 1.5;
}

.upload-tip p {
  margin: 4px 0;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
}

.recognition-result {
  margin-top: 24px;
}

.recognition-details {
  margin-top: 16px;
}

.detail-section {
  margin-bottom: 16px;
}

.detail-section h4 {
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.detail-section pre {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 6px;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.submit-section {
  margin-top: 32px;
  text-align: center;
}

/* 美化表单元素 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #334155;
  font-size: 16px;
}

:deep(.el-input__wrapper) {
  border-radius: 12px;
  border: 2px solid #e1e5e9;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #667eea;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.el-button) {
  border-radius: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
  padding: 12px 32px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

:deep(.el-upload--picture-card) {
  border-radius: 12px;
  border: 2px dashed #d9d9d9;
  transition: all 0.3s ease;
}

:deep(.el-upload--picture-card:hover) {
  border-color: #667eea;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .vehicle-register-bg {
    padding: 16px;
  }
  
  .vehicle-register-card {
    padding: 24px;
    border-radius: 16px;
  }
  
  .vehicle-register-title {
    font-size: 24px;
  }
}
</style>
